<?php
// +----------------------------------------------------------------------
// | HkCms 后台用户模型
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\admin\model;

use common\model\Model;
use app\admin\validate\User as UserValidata;
use think\Db;

class User extends Model
{      

    protected static function init()
    {   
        User::event('after_insert', function ($data) {

            Db::name('User')->where('id' ,$data['id'])

                ->update([

                    'password' => md5($data['password'] . md5($data['verify'])),
                ]);
        });
    }

    /**
     * 获取用户信息
     * @param $identifier
     * @param null $password
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function getUserInfo($identifier, $password = NULL)
    {
        if (empty($identifier)) {
            return false;
        }
        $map = array();
        //判断是uid还是用户名
        if (is_int($identifier)) {
            $map['id'] = $identifier;
        } else {
            $map['username'] = $identifier;
        }
        $userInfo = $this->where($map)->find();
        if (empty($userInfo)) {
            return false;
        }
        //密码验证
        if (!empty($password) && $this->hashPassword($password, $userInfo['verify']) != $userInfo['password']) {
            return false;
        }
        return $userInfo->toArray();
    }

    /**
     * 更新登录状态信息
     * @param integer $userId
     * @return string
     */
    public function loginStatus($userId)
    {
        $model = $this->where(['id'=>(int) $userId])->find();
        $model->last_login_time = time();
        $model->last_login_ip = request()->ip();
        return $model->save();
    }

    /**
     * 对明文密码，进行加密，返回加密后的密文密码
     * @param string $password 明文
     * @param string $verify 认证码
     * @return string 密文
     */
    public function hashPassword($password, $verify = "")
    {
        return md5($password . md5($verify));
    }

    /**
     * 修改密码
     * @param int $uid 用户ID
     * @param string $newPass 新密码
     * @param string $password 旧密码
     * @return boolean
     */
    public function changePassword($uid, $newPass, $password = NULL)
    {
        //获取会员信息
        $userInfo = $this->getUserInfo((int) $uid, $password);
        if (empty($userInfo)) {
            $this->error = '旧密码不正确或者该用户不存在！';
            return false;
        }
        $verify = genRandomString(6);
        $status = $this->save([
            'password' => $this->hashPassword($newPass, $verify), 'verify' => $verify
        ],['id' => $userInfo['id']]);
        return $status !== false ? true : false;
    }

    /**
     * 创建管理员
     * @param type $data
     * @return boolean
     */
    public function createManager($data) 
    {

        if (empty($data)) {

            $this->error = '没有数据！';

            return false;
        }

        $validate = new UserValidata;

        $result = $validate->check($data);

        // 验证数据
        if(!$result){

            $this->error = $validate->getError();

            return false;
        }

        $data['create_time'] = time();

        $data['verify'] = time();

        // 添加
        $id = $this->data($data)->allowField(true)->save();

        if ($id) {

            return $id;
        }

        $this->error = '入库失败！';

        return false;
    }

    /**
     * 删除管理员
     * @param type $userId
     * @return boolean
     */
    public function deleteUser($userId) 
    {
        $userId = (int) $userId;

        if (empty($userId)) {

            $this->error = '请指定需要删除的用户ID！';

            return false;
        }

        if ($userId == 1) {

            $this->error = '该管理员不能被删除！';

            return false;
        }

        if (false !== $this->where('id',$userId)->delete()) {

            return true;

        } else {

            $this->error = '删除失败！';

            return false;
        }
    }

    /**
     * 修改管理员信息
     * @param type $data
     */
    public function amendManager($data) 
    {

        if (empty($data) || !is_array($data) || !isset($data['id'])) {

            $this->error = '没有需要修改的数据！';

            return false;
        }

        $info = $this->where(array('id' => $data['id']))->find()->toArray();

        if (empty($info)) {

            $this->error = '该管理员不存在！';

            return false;
        }

        // 如果名字有修改
        if ( $data['username'] !== $info['username'] ) {

            $find = $this->where('username', $data['username'])->find();

            if( $find ){

                $this->error = '该用户名已存在';

                return false;
            }
        }

        //密码为空，表示不修改密码
        if (isset($data['password']) && empty($data['password'])) {

            unset($data['password']);
        }else{

            $verify = genRandomString(6);

            $data['verify'] = $verify;

            $data['assword'] = $this->hashPassword($this->password, $verify);
        }

        $validate = new UserValidata;

        $result = $validate->scene('edit')->check($data);

        // 验证数据
        if(!$result){

            $this->error = $validate->getError();

            return false;
        }

        unset($data['pwdconfirm']);

        $status = $this->update($data);

        return $status !== false ? true : false;
      
    }
}